﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GestionBudget.Objects;

namespace GestionBudget.Controls
{
    public partial class ucTransaction : ControlObject
    {
        private object CellValue;
        private List<Transaction> listeTransactionDataSource;
        private bool erreur;

        public ucTransaction()
        {
            InitializeComponent();
            FormatDateTimePicker("MMMM yyyy");

            dgvTransactions.AutoGenerateColumns = false;

            DataGridViewComboBoxColumn sousCatColumn = (DataGridViewComboBoxColumn)dgvTransactions.Columns["cSousCategorie"];
            sousCatColumn.DisplayMember = "Description";
            sousCatColumn.ValueMember = "Self";
            sousCatColumn.DataPropertyName = "SousCategorie";
        }

        private void dgvTransactions_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            erreur = true;
            MessageBox.Show("La valeur n'est pas valide.", "Attention", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }

        public override string TitreControl
        {
            get
            {
                return "Gestion des transactions";
            }
        }

        public override bool Ajouter()
        {
            if (Securite.ProfilCourant.ListeSousCategorie.Count != 0)
            {
                Transaction tr = Transaction.Creer();
                tr.AttribuerIdentifiant();
                tr.Profil = Securite.ProfilCourant;

                ChargerListe();

                return true;
            }
            else
            {
                MessageBox.Show("Vous devez avoir au moins une sous-catégorie de créée pour pouvoir ajouter une transaction", "Attention", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
        }

        public override void Sauvegarder()
        {
            dgvTransactions.EndEdit();

            if (!erreur)
            {
                foreach (ObjectPersistent profil in DictionnaireDonnees.ListeTransactions.Where(pr => pr.EstNouveau || pr.EstModifie))
                {
                    profil.Sauvegarder();
                }

                ChargerListe();
            }
        }

        public override bool Supprimer()
        {
            if (dgvTransactions.SelectedRows.Count > 0)
            {
                foreach (DataGridViewRow selectedRow in dgvTransactions.SelectedRows)
                {
                    DictionnaireDonnees.Supprimer((ObjectPersistent)selectedRow.DataBoundItem);
                }

                ChargerListe();
                return true;
            }
            else
            {
                return false;
            }

        }

        public override void ChargerListe()
        {
            DataGridViewComboBoxColumn sousCatColumn = (DataGridViewComboBoxColumn)dgvTransactions.Columns["cSousCategorie"];
            sousCatColumn.DataSource = Securite.ProfilCourant.ListeSousCategorie;

            listeTransactionDataSource = Securite.ProfilCourant.ListeTransaction.ToList();
            dgvTransactions.DataSource = listeTransactionDataSource;
            dgvTransactions.Columns["cMontant"].HeaderText = String.Format("Montant ({0})", Securite.ProfilCourant.Devise.DescriptionLongue);

            optMontantDeviseAffic.Text = Securite.ProfilCourant.Devise.Symbole;

            CalculerTransaction();
        }

        private void CalculerTransaction()
        {
            decimal revenu;
            decimal depense;
            decimal total;
            string symbole = Securite.ProfilCourant.Devise.Symbole;

            if (listeTransactionDataSource != null)
            {
                revenu = listeTransactionDataSource.Where(tr => tr.SousCategorie.EstRevenu).Sum(tr => tr.Montant);
                depense = listeTransactionDataSource.Where(tr => !tr.SousCategorie.EstRevenu).Sum(tr => tr.Montant);

                total = revenu - depense;

                if (total < 0)
                {
                    lblMontantTotal.ForeColor = Color.Red;
                    llblCompression.Visible = true;
                }
                else
                {
                    lblMontantTotal.ForeColor = Color.Green;
                    llblCompression.Visible = false;
                }

                if (optMontantPourcentAffic.Checked)
                {
                    total = revenu + depense;
                    
                    revenu = (revenu != 0 ? ((revenu * 100) / total) : 0);
                    depense = (depense != 0 ? ((depense * 100) / total) : 0);
                    total = revenu + depense;
                    symbole = "%";
                }

                lblMontantRevenu.Text = String.Format(lblMontantRevenu.Tag.ToString(), Math.Round(revenu, 2), symbole);
                lblMontantDepense.Text = String.Format(lblMontantDepense.Tag.ToString(), Math.Round(depense, 2), symbole);
                lblMontantTotal.Text = String.Format(lblMontantTotal.Tag.ToString(), Math.Round(total, 2), symbole);
                
                
            }
        }

        private void dgvTransactions_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            erreur = false;
            DataGridView dgv = sender as DataGridView;
            object nouvelleValeur;

            if (dgv.CurrentCell != null && CellValue != null)
            {
                nouvelleValeur = dgv.CurrentCell.Value;
                if ((CellValue.Equals(nouvelleValeur)) && (!String.IsNullOrEmpty(nouvelleValeur.ToString())))
                {
                    (this.Parent as FormPrincipal).GestionBouton();
                }
                else if (String.IsNullOrEmpty(nouvelleValeur.ToString()))
                {
                    dgv.CurrentCell.Value = CellValue;
                }

                dgv.Refresh();
            }

            CalculerTransaction();
        }

        private void dgvTransactions_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            CellValue = Convert.ToString((sender as DataGridView).CurrentCell.Value);
        }

        private void btAfficherParDates_Click(object sender, EventArgs e)
        {
            DateTime dateDebut = dtpDebut.Value.AddDays(-(dtpDebut.Value.Day - 1));
            DateTime dateFin = dtpFin.Value.AddDays(-(dtpFin.Value.Day - 1));

            listeTransactionDataSource = Securite.ProfilCourant.ListeTransaction.Where(
                                            trans => trans.Date >= dateDebut || !dtpDebut.Checked).ToList();
            if (dtpFin.Checked && (dateFin.Date >= dateDebut.Date || !dtpDebut.Checked))
            {
                listeTransactionDataSource = listeTransactionDataSource.Intersect(Securite.ProfilCourant.ListeTransaction.Where(
                                                transaction => transaction.Date <= dateFin || !dtpFin.Checked)).ToList();
            }
            else if(dtpFin.Checked)
            {
                MessageBox.Show("Les mois choisis sont invalides!", "Attention", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

            dgvTransactions.DataSource = listeTransactionDataSource;
            CalculerTransaction();
        }

        private void btReinitialiser_Click(object sender, EventArgs e)
        {
            dtpDebut.Value = DateTime.Now;
            dtpFin.Value = DateTime.Now;
            dtpDebut.Checked = false;
            dtpFin.Checked = false;
            ChargerListe();
        }

        private void FormatDateTimePicker(string format)
        {
            dtpDebut.Format = DateTimePickerFormat.Custom;
            dtpDebut.CustomFormat = format;

            dtpFin.Format = DateTimePickerFormat.Custom;
            dtpFin.CustomFormat = format;
        }

        private void llblCompression_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            gbCompression.Visible = true;

            cmbCompressionSousCategorie.DataSource = listeTransactionDataSource.Select(trans => trans.SousCategorie).Where(sc => sc.EstCompressible).ToList();
            cmbCompressionSousCategorie.DisplayMember = "Description";
            cmbCompressionSousCategorie.ValueMember = "Identifiant";
        }

        private void CalculerCompression()
        {
            decimal depenseSousCatCompresse;
            decimal depenseSousCatNonCompresse;
            decimal depenseRetire;
            decimal revenu;
            decimal depenseSansSousCatCompresse;
            decimal total;
            string symbole = Securite.ProfilCourant.Devise.Symbole;

            if (String.IsNullOrEmpty(nudPourcentageCompression.Text))
            {
                nudPourcentageCompression.Text = "0%";
            }

            gbPrevisualisationCompression.Visible = true;

            depenseSousCatNonCompresse = listeTransactionDataSource.Where(tr => String.Equals(tr.SousCategorie.Description, cmbCompressionSousCategorie.Text)).Sum(tr => tr.Montant);
            depenseRetire = (depenseSousCatNonCompresse * (nudPourcentageCompression.Value / 100m));
            depenseSousCatCompresse = depenseSousCatNonCompresse - depenseRetire;
            revenu = listeTransactionDataSource.Where(tr => tr.SousCategorie.EstRevenu).Sum(tr => tr.Montant);
            depenseSansSousCatCompresse = listeTransactionDataSource.Where(tr => (!tr.SousCategorie.EstRevenu) && (!String.Equals(tr.SousCategorie.Description,cmbCompressionSousCategorie.Text))).Sum(tr => tr.Montant);
            total = revenu - (depenseSansSousCatCompresse + depenseSousCatCompresse);

            lblMontantDepenseAvantCompression.Text = String.Format(lblMontantDepenseAvantCompression.Tag.ToString(), (double)depenseSousCatNonCompresse, symbole);
            lblMontantRetirerCompression.Text = String.Format(lblMontantRetirerCompression.Tag.ToString(), (double)depenseRetire, symbole);
            lblMontantDepenseCompression.Text = String.Format(lblMontantDepenseCompression.Tag.ToString(), (double)depenseSousCatCompresse, symbole);
            lblNouveauMontantTotal.Text = String.Format(lblNouveauMontantTotal.Tag.ToString(), (double)total, symbole);

            lblNouveauMontantTotal.ForeColor = (total < 0 ? Color.Red : Color.Green);

        }

        private void cmdSauvegardeCompression_Click(object sender, EventArgs e)
        {
            foreach (Transaction tr in listeTransactionDataSource.Where(tr => String.Equals(tr.SousCategorie.Description,cmbCompressionSousCategorie.Text)).ToList())
            {
                tr.Montant = tr.Montant * ((100m - nudPourcentageCompression.Value) / 100m);
            }

            Sauvegarder();

            gbCompression.Visible = false;
        }

        private void Grp_optMontantAffichage(object sender, EventArgs e)
        {
            CalculerTransaction();
        }

        private void nudPourcentageCompression_ValueChanged(object sender, EventArgs e)
        {
            CalculerCompression();
        }
    }
}
